package com.example.pei.ithinklearnt.present;

import android.content.Context;
import android.content.SharedPreferences;

import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.bean.praises;
import com.example.pei.ithinklearnt.bean.shielding;
import com.example.pei.ithinklearnt.model.AlumniCircleModel;
import com.example.pei.ithinklearnt.model.AlumniCircleModelImp;
import com.example.pei.ithinklearnt.model.PraiseModel;
import com.example.pei.ithinklearnt.model.PraiseModelImp;
import com.example.pei.ithinklearnt.view.interfaces.HomeInterface;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;


import static com.example.pei.ithinklearnt.utils.MyUtils.AppRunTime;


public class HomePresentImp implements HomePresent{

    private HomeInterface homeInterface;
    private AlumniCircleModel alumniCircleModel;
    private PraiseModel praiseModel;

    private UserInfo currentUser;
    private Date oldestDynamicDate;  //最老的动态时间


    private static final int STATE_REFRESH = 0;// 下拉刷新
    private static final int STATE_MORE = 1;// 加载更多

    private KProgressHUD hud; //等待进度条

    private boolean isFirst=true;   //第一次进入应用

    public HomePresentImp(HomeInterface homeInterface){
        this.homeInterface=homeInterface;
        this.alumniCircleModel=new AlumniCircleModelImp();
        this.praiseModel=new PraiseModelImp();
    }


    @Override
    public void initDate() {
        currentUser=AppApplication.getCurrentUser();
        if(AppRunTime()==1) {                           //整个程序是第一次运行，则从服务器上下载
            downLoadUserPraises();      //打开应用时从服务器上获取此用户点赞的动态
            downLoadUserShieldings();   //打开应用时从服务器上获取此用户屏蔽的动态
        }

        refresh();            //从服务器拉数据

    }


    @Override
    public void queryData(final int actionType, int limit, final boolean isHint) {
        BmobQuery<AlumniCircle> query = new BmobQuery<>();
        // 按时间降序查询
        query.order("-createdAt");
        query.include("sender");   //发送者信息也需要查询出来
        // 如果是加载更多
        if (actionType == STATE_MORE) {
             //只查询小于等于最后一个item发表时间的数据
               if(oldestDynamicDate!=null) {
                  // query.addWhereLessThanOrEqualTo("createdAt", new BmobDate(oldestDynamicDate));
                   query.addWhereLessThan("createdAt", new BmobDate(oldestDynamicDate));
               }
        }
        // 设置每页数据个数
        query.setLimit(limit);
//        if(isFirst){
//            isFirst=false;  //之后不再是第一次进入的刷新
//            boolean isCache = query.hasCachedResult(AlumniCircle.class);
//            if(isCache){    //第一次进入且有缓存
//                if(isNetworkAvailable(AppApplication.getContext())){   //网络可用
//                    query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ELSE_NETWORK );   //
//                }else {
//                    query.setCachePolicy(BmobQuery.CachePolicy.CACHE_ONLY );   //
//                }
//            }else{
//                query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
//            }
//        }else{
//            query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
//        }
//        query.setMaxCacheAge(TimeUnit.DAYS.toMillis(30));//此表示缓存三十天
        // 查找数据
        query.findObjects(new FindListener<AlumniCircle>() {
            @Override
            public void done(List<AlumniCircle> Serverlist, BmobException e) {
                if(e==null){
                    if (Serverlist.size() > 0) {
                     //   List <String >senderNames=new ArrayList<>();
                        if (actionType == STATE_REFRESH) {
                            // 当是下拉刷新操作时,清空adaper，重新添加数据
                            homeInterface.getAdapter().clearDate();
                            //设置下拉刷新结束
                            homeInterface.finishRefresh(true);
                        }else{
                            //设置上拉加载更多结束
                            homeInterface.finishLoadMore(true);
                        }
                        // 将本次查询的数据添加到adapter中
                        for (AlumniCircle td : Serverlist) {
                            if(!alumniCircleModel.isDynamicShielded(td.getObjectId(),currentUser.getUsername())) {
                                if (td.getSender() != null) {
                                    //不是屏蔽的信息则可以进行添加
                                    if (praiseModel.isDynamicPraiseed(td.getObjectId(), currentUser.getUsername())) {
                                        //被点赞的
                                        td.setIsPraise(1);
                                    } else {
                                        td.setIsPraise(0);
                                    }
                                    homeInterface.getAdapter().addDatetoFoot(td);
                                }
                            }
                        }
                        // 更新最老的数据时间// 处理时间查询
                        String lastTime = Serverlist.get(Serverlist.size() - 1).getCreatedAt();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            oldestDynamicDate = sdf.parse(lastTime);
                        } catch (ParseException ee) {
                            ee.printStackTrace();
                        }
                        if (actionType == STATE_REFRESH) {
                            homeInterface.adapterNotifyDataSetChanged();     //刷新
                            //如果刷新完数量太少，那么自动加载更多(万一有傻逼屏蔽了所有最新的动态
                            if(homeInterface.getAdapter().getmList().size()<=5){
                                queryData(STATE_MORE,10,false);
                            }
                        }else{
                            //同上
                            if(Serverlist.size()<=5){
                                queryData(STATE_MORE,10,false);
                            }
                        }
                    } else if (actionType == STATE_MORE) {
                        if(isHint)
                            Toast.makeText(homeInterface.getActivityy(),"o(*////▽////*)q 死鬼，已经到人家底线啦",Toast.LENGTH_SHORT).show();
                        homeInterface.finishLoadMore(true);
                    } else if (actionType == STATE_REFRESH) {
                        if(isHint)
                            Toast.makeText(homeInterface.getActivityy(),"没有数据",Toast.LENGTH_SHORT).show();
                        homeInterface.finishRefresh(true);
                    }
                }else{
                    //错误
                    if (actionType == STATE_MORE) {
                        homeInterface.finishLoadMore(false);
                        Toast.makeText(homeInterface.getActivityy(),"加载失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }else {
                        homeInterface.finishRefresh(false);
                        Toast.makeText(homeInterface.getActivityy(),"刷新失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    }
                }
            }

        });
    }

    @Override
    public void deleteAlumniCircle(final int position, final deleteAlumniCircleListener listener) {
        hud = KProgressHUD.create(homeInterface.getActivityy())
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("正在删除...")
                .setCornerRadius(10)
                .show();
        //删除某个动态及相关图片
        alumniCircleModel.deleteAlumniCircle( homeInterface.getAdapter().getmList().get(position),
                                                homeInterface.getAdapter().getmList().get(position).getphotos(),
                                                new AlumniCircleModelImp.deleteAlumniCircle() {
                    @Override
                    public void succeed() {
                        listener.succeed();
                        hud.dismiss();
                    }

                    @Override
                    public void failed() {
                        listener.failed();
                        hud.dismiss();
                    }
                });
    }

    @Override
    public void shieldAlumniCircle(final int position) {
        //不管是否操作成功，我都先应该移除这个item
        homeInterface.getAdapter().getmList().remove(position);
        homeInterface.getAdapter().notifyItemRemoved(position);
        homeInterface.getAdapter().notifyItemRangeChanged(position,homeInterface.getAdapter().getmList().size()-position);

        alumniCircleModel.shieldAlumniCircle(currentUser.getUsername(), homeInterface.getAdapter().getmList().get(position).getObjectId(),
                new AlumniCircleModelImp.shieldAlumniCircle() {
                    @Override
                    public void succeed() {

                    }
                    @Override
                    public void failed() {
                        Toast.makeText(homeInterface.getActivityy(),"请检查网络配置...",Toast.LENGTH_SHORT).show();
                    }
                });
    }


    @Override
    public void praiseAlumniCircle(final int position) {
        //服务器上查看是否从未点赞状态变成改变状态
        praiseModel.praiseAlumniCircle(currentUser.getUsername(), homeInterface.getAdapter().getmList().get(position).getObjectId(),
                new PraiseModelImp.praiseAlumniCircle() {
                    @Override
                    public void becomePraised() {
                        //未点赞状态变成点赞状态
                        homeInterface.getAdapter().getmList().get(position).setIsPraise(1);
                        homeInterface.getAdapter().notifyItemChanged(position,1);
                    }
                });
        alumniCircleModel.addOneLike( homeInterface.getAdapter().getmList().get(position).getObjectId());

        int count=homeInterface.getAdapter().getmList().get(position).getPraiseNumber();
        count++;
        homeInterface.getAdapter().getmList().get(position).setPraiseNumber(count);
        homeInterface.getAdapter().notifyItemChanged(position,1);

    }



    @Override
    public void refresh() {
        queryData(STATE_REFRESH,15,true);

    }

    @Override
    public void loadmore() {
        queryData(STATE_MORE,10,true);

    }

    @Override
    public void refreshOnlyOne(final int position) {
        //要刷新的objectId
        final String objectId=homeInterface.getAdapter().getmList().get(position).getObjectId();
        final int isPraised=homeInterface.getAdapter().getmList().get(position).getIsPraise();
        alumniCircleModel.findAlumniCircleByObjectId(objectId, new AlumniCircleModelImp.findAlumniCircle() {
            @Override
            public void success(AlumniCircle object) {
                //更新adapter的内容
                homeInterface.getAdapter().getmList().set(position,object);
                homeInterface.getAdapter().getmList().get(position).setIsPraise(isPraised);
                homeInterface.getAdapter().getmList().get(position).setIsPraise(praiseModel.isDynamicPraiseed(objectId,currentUser.getUsername())?1:0);
                //刷新
                homeInterface.adapterNotifyDataOneChange(position);
            }

            @Override
            public void failed(BmobException e) {

            }
        });

    }





    private void downLoadUserPraises() {
        BmobQuery<praises> query = new BmobQuery<praises>();
        query.addWhereEqualTo("userID", currentUser.getUsername());
        //执行查询方法
        query.findObjects(new FindListener<praises>() {
            @Override
            public void done(final List<praises> object, BmobException e) {
                if (e == null) {
                    final SharedPreferences.Editor editor=homeInterface.getActivityy().getSharedPreferences(currentUser.getUsername()+"_praises", Context.MODE_PRIVATE).edit();
                    if(object.size()==1){
                        //服务器存在用户的信息，下载到本地
                        for(int i=0;i<object.get(0).getObjectIDs().size();i++) {
                            editor.putInt(object.get(0).getObjectIDs().get(i).toString(),1);
                        }
                        editor.apply();
                    }
                }
            }
        });

    }

    private void downLoadUserShieldings() {
        BmobQuery<shielding> query = new BmobQuery<shielding>();
        query.addWhereEqualTo("userID", currentUser.getUsername());
        //执行查询方法
        query.findObjects(new FindListener<shielding>() {
            @Override
            public void done(final List<shielding> object, BmobException e) {
                if (e == null) {
                    final SharedPreferences.Editor editor = homeInterface.getActivityy().getSharedPreferences(currentUser.getUsername() + "_shieldings", Context.MODE_PRIVATE).edit();
                    if (object.size() == 1) {
                        //服务器存在用户的信息，下载到本地
                        editor.putInt("size", object.get(0).getObjectIDs().size());
                        for (int i = 0; i < object.get(0).getObjectIDs().size(); i++) {
                            editor.putString("num_" + i, object.get(0).getObjectIDs().get(i).toString());
                        }
                        editor.apply();
                    } else if (object.size() == 0) {
                        //服务器没有找个人的屏蔽数据
                    }
                }
            }
        });

    }



}
